from google.appengine.ext import webapp
from ft_table import FtTable
from testing import get_request
import dlz_config as dc


def cleanTestLocation(text):
    '''
    replace common errors
    '''
    
    
    replace_list = [('Of', 'of'),
                    ('Cl', 'CL'),
                    ('cl', 'CL'),
                    ('Ft', 'ft')]
    
    return replaceWords(replace_list, text.title())

def replaceWords(replace_list, text):
    '''
    split a sentence into words, and replace words with corrected ones
    '''
    parts = text.split()
    results = []
    for part in parts:
        for (f,r) in replace_list:
            if part==f:
                part = r
            
        results.append(part) 
        
    return ' '.join(results)

def cleanTestInterval(text):
    '''
    common test interval errors
    '''
    replace_list = [('BEG', 'Below Existing Grade'),
                    ('beg', 'Below Existing Grade'),
                    ('AB', 'Aggregate Base'),
                    ('ab', 'Aggregate Base'),
                    ('S/G', 'Subgrade'),
                    ('SG', 'Subgrade'),
                    ('sg', 'Subgrade'),
                    ('s/g', 'Subgrade')]
    return replaceWords(replace_list, text).title()

def processCompaction(records):
    row1, row2 = dc.get_dlz_compaction_schema()
    import csv, StringIO
    out = StringIO.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    writer.writerow(row1)
    writer.writerow(row2)
    for record in records:
        row = []
        for fld in row1:
            value = record[fld]
            if fld=='test_location':
                value = cleanTestLocation(value)
            if fld=='test_interval':
                value = cleanTestInterval(value)
            if fld=='project_number':
                value = "'%s" % value 
            
            row.append(value)
        writer.writerow(row)
         
    results = out.getvalue()
    out.close()
    return results

class DownloadHandler(webapp.RequestHandler):

    def get(self):
        self.post()
    def post(self):
        request = get_request(self.request)        
        format = self.request.get('format')
        if format=='csv':
            #download in csv format, ignore the start and limit
            request['start'] = ''
            request['limit'] = ''
            ft = FtTable(None, None, int(dc.get('DLZ_COMPACTION_JOIN')['ft_table_id']))
            records = ft.get_records(request, True)
            csv_text = processCompaction(records)
            self.response.headers["Content-Type"] = "application/octet-stream"
            self.response.headers["Content-Disposition"] = "attachment;Filename=compaction.csv"  
            self.response.headers["Cache-Control"] = "no-store, no-cache, no-transform, must-revalidate, private"
            self.response.out.write(csv_text)
